<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="5">
              <a-form-item label="部门" prop="type">
                <a-tree-select
                  v-model="queryParam.deptId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="deptOptions"
                  placeholder="请选择"
                  :replaceFields="{
                    children: 'children',
                    title: 'menuName',
                    key: 'id',
                    value: 'id',
                  }"
                  @change="onMenuTreeChange"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="客户经理">
                <a-select
                  placeholder="请选择客户经理"
                  v-model="queryParam.userId"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="d in userNamesList"
                    :key="d.name"
                    :value="d.id"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="客户姓名">
                <a-input
                  v-model="queryParam.cusName"
                  placeholder="请输入客户姓名"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="客户电话">
                <a-input
                  v-model="queryParam.phone"
                  placeholder="请输入客户姓名"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="上门时间">
                <a-date-picker
                  v-model="queryParam.beginToHomeTime"
                  valueFormat="YYYY-MM-DD"
                  :show-today="true"
                  placeholder="选择日期"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />刷新</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 增加 -->
      <biz-to-home-add-form
        v-if="showAddModal"
        ref="bizToHomeAddForm"
        @ok="getList"
        @close="showAddModal = false"
      />
      <!-- 编辑 -->
      <biz-to-home-edit-form
        v-if="showEditModal"
        ref="bizToHomeEditForm"
        @ok="getList"
        @close="showEditModal = false"
      />
      <advance-table
        title="预约上门"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        tableKey="base-bizToHome-index-table"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="bizToHomeList"
        :loading="loading"
        :format-conditions="true"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      >
        <div class="table-operations" slot="button">
          <a-button type="primary" @click="handlezuofei">
            <a-icon type="delete" />作废
          </a-button>
        </div>

        <span slot="operation" slot-scope="{ text, record }">
          <a-button-group>
            <a-button
              type="link"
              icon="form"
              @click="handleShowToHomeUser(record)"
              v-if="record.status == '0'"
            >
              签到
            </a-button>
            <a-divider type="vertical" v-if="record.status == '0'" />
            <a-button
              type="link"
              icon="search"
              @click="handleShowToHomeUser(record)"
            >
              查看
            </a-button>
          </a-button-group>
        </span>

        <span slot="inviteCode" slot-scope="{ record }">
          <a-tag v-if="record.isSms == 1" color="#87d068">
            {{ record.inviteCode }}
          </a-tag>
          <a-tag v-else>无 </a-tag>
        </span>
        <span slot="tuofei" slot-scope="{ text }">
          <a-tag v-if="text == 0" color="#87d068"> 未作废 </a-tag>
          <a-tag v-else color="red">作废 </a-tag> </span
        ><span slot="status" slot-scope="{ text }">
          <a-tag v-if="text == '0'" color="#e6a23c"> 待上门 </a-tag>
          <a-tag v-else color="#87d068">已上门 </a-tag>
        </span>
        <span slot="cusName" slot-scope="{ text, record }">
          <a-tag
            v-if="record.status == '1'"
            color="red"
            @click="handleShowQyFanKui(record)"
            >客户上门反馈</a-tag
          >
          &nbsp;
          <span style="color: #f8643f">{{ text }}</span>
        </span>
        <span slot="qyStatus" slot-scope="{ text }">
          <a-tag v-if="text == '0'">未设置</a-tag>
          <a-tag v-if="text == '1'" color="#e6a23c">未签约</a-tag>
          <a-tag v-if="text == '2'" color="#87d068">已签约</a-tag>
        </span>
        <span slot="companyNames" slot-scope="{ text }">
          <a-tag v-for="(item, i) in JSON.parse(text)" :key="i">{{
            item
          }}</a-tag>
        </span>

        <span slot="yuyueTime" slot-scope="{ text, record }">
          <a-date-picker
            show-time
            :default-value="text"
            v-if="record.status == 0"
            @change="
              (date, dateString) => updateyuyueDate(date, dateString, record)
            "
            @ok="updateyuyueDateOk"
          />
          <a-date-picker show-time :default-value="text" disabled v-else />
        </span>
      </advance-table>
    </a-card>

    <a-modal
      :visible="visible"
      title="设置人员"
      v-if="visible"
      width="650px"
      @ok="
        visible = false;
        getList();
      "
      @cancel="
        visible = false;
        getList();
      "
    >
      <a-row>
        <a-col :span="2" style="margin: -10px 15px 10px 15px">
          <a-button
            type="primary"
            @click="chooseUserVisible = true"
            v-if="toHome.status == '0'"
            >添加人员</a-button
          >
        </a-col>
        <a-col :span="24">
          <a-table :data-source="toHomeUserList" bordered size="middle">
            <a-table-column
              key="dName"
              title="部门"
              data-index="dname"
              width="120px"
            />
            <a-table-column
              key="uName"
              title="姓名"
              data-index="uname"
              width="120px"
            />
            <a-table-column
              key="createTime"
              title="添加时间"
              data-index="createTime"
              width="190px"
            />
            <a-table-column
              title="操作"
              width="100px"
              v-if="toHome.status == '0'"
            />
          </a-table>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal
      :visible="chooseUserVisible"
      title="选择人员"
      v-if="chooseUserVisible"
      width="55%"
      @ok="handleAddToHomeUsers"
      @cancel="chooseUserVisible = false"
      :dialog-style="{ top: '10px' }"
    >
      <change-user @getUser="handleManualShare" :isCheckBox="true" />
    </a-modal>

    <a-modal
      :visible="visibleShowQyStatus"
      title="客户上门反馈"
      v-if="visibleShowQyStatus"
      width="550px"
      @ok="handleUpdateToHome"
      @cancel="visibleShowQyStatus = false"
    >
      <a-row style="widows: 85%; margin-left: 7%">
        <a-col :span="24">
          <a-form-item label="是否签单:">
            <a-radio-group name="radioGroup" v-model="toHome.qyStatus">
              <a-radio :value="1"> 未签单 </a-radio>
              <a-radio :value="2"> 已签单 </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="结果反馈:">
            <a-textarea
              v-model="toHome.remark"
              placeholder="请填写客户上门反馈，未签单需填写原因，已签单填写沟通结果"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import {
  listBizToHome,
  delBizToHome,
  exportBizToHome,
  updateBizToHome,
} from "@/api/biz/bizToHome";
import {
  listBizToHomeUser,
  delBizToHomeUser,
  addBizToHomeUser,
} from "@/api/biz/bizToHomeUser";
import { listUser } from "@/api/system/user";
import { listDeptTree } from "@/api/system/dept";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import BizToHomeAddForm from "@/views/biz/tohome/modules/BizToHomeAddForm";
import BizToHomeEditForm from "@/views/biz/tohome/modules/BizToHomeEditForm";
import ChangeUser from "@/views/system/user/modules/ChangeUser";
export default {
  name: "BizToHome",
  components: {
    AdvanceTable,
    BizToHomeAddForm,
    BizToHomeEditForm,
    ChangeUser,
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      visible: false,
      chooseUserVisible: false,
      visibleShowQyStatus: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 预约上门表格数据
      bizToHomeList: [],
      // 修改上门信息
      toHomeInfo: {},
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,

        beginToHomeTime: undefined,
      },
      toHome: { isFanKui: 0 },
      toHomeUserList: [],
      toHomeUserForm: {
        qdUsers: [],
        customerId: "",
        tohomeId: "",
      },
      shangmenFanKui: "",
      qyStatus: 1,
      columns: [
        {
          title: "客户经理",
          dataIndex: "userName",
          ellipsis: true,
          align: "left",
          width: "120px",
        },
        {
          title: "客户姓名",
          dataIndex: "cusName",
          ellipsis: true,
          align: "left",
          width: "190px",
          scopedSlots: { customRender: "cusName" },
        },

        {
          title: "是否作废",
          dataIndex: "tuofei",
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "tuofei" },
        },
        {
          title: "邀请码",
          dataIndex: "inviteCode",
          align: "center",
          width: "80px",
          scopedSlots: { customRender: "inviteCode" },
        },
        {
          title: "预约时间",
          dataIndex: "yuyueTime",
          align: "center",
          width: "220px",
          scopedSlots: { customRender: "yuyueTime" },
        },
        {
          title: "上门时间",
          dataIndex: "toHomeTime",
          align: "center",
          width: "200px",
        },
        {
          title: "是否上门",
          dataIndex: "status",
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "status" },
        },
        {
          title: "上门门店",
          dataIndex: "companyNames",
          align: "center",
          width: "230px",
          scopedSlots: { customRender: "companyNames" },
        },
        {
          title: "签单状态",
          dataIndex: "qyStatus",
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "qyStatus" },
        },
        {
          title: "上门反馈",
          dataIndex: "remark",
          align: "left",
          width: "225px",
        },
        {
          title: "接待人员",
          dataIndex: "operation",
          align: "left",
          width: "175px",
          scopedSlots: { customRender: "operation" },
          fixed: "right",
        },
      ],
      deptOptions: [],
      userNamesList: [],
    };
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    getUserList(deptId) {
      listUser({ deptId: deptId, pageSize: 100 }).then((res) => {
        this.userNamesList = res.data.list;
      });
    },
    onMenuTreeChange(value) {
      console.log(value);
      this.getUserList(value);
    },
    getDeptList() {
      listDeptTree("", 3).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    // 提交反馈
    handleUpdateToHome() {
      this.toHome.isFanKui = "1";
      updateBizToHome(this.toHome).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功", 3);
          this.getList();
          this.toHome = { remark: "", qyStatus: "", isFanKui: "0" };
        }
      });
      this.visibleShowQyStatus = false;
    },
    // 客户反馈
    handleShowQyFanKui(item) {
      this.toHome = item;
      this.visibleShowQyStatus = true;
    },
    // 显示上门信息
    handleShowToHomeUser(item) {
      this.toHome = item;
      this.toHomeUserForm.customerId = item.customerId;
      this.toHomeUserForm.tohomeId = item.id;
      this.visible = true;
      this.handleToHomeUsersList();
    },
    // 添加签到
    handleAddToHomeUsers() {
      this.chooseUserVisible = false;
      addBizToHomeUser(this.toHomeUserForm).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功", 3);
        }
        this.handleToHomeUsersList();
      });
    },
    // 删除签到
    handleDelToHomeUsers() {
      delBizToHomeUser().then((res) => {});
    },
    // 获取签到人员
    handleToHomeUsersList() {
      listBizToHomeUser({
        customerId: this.toHomeUserForm.customerId,
        tohomeId: this.toHomeUserForm.tohomeId,
      }).then((res) => {
        this.toHomeUserList = res.data.list;
      });
    },
    // 获取选择后的人员信息
    handleManualShare(users) {
      console.log(users);
      this.toHomeUserForm.qdUsers = users.map((item) => {
        return {
          userName: item.name,
          deptName: item.sysDept.deptName,
          userId: item.id,
          deptId: item.sysDept.id,
        };
      });
    },
    /** 查询预约上门列表 */
    getList() {
      this.loading = true;
      listBizToHome(this.queryParam).then((response) => {
        this.bizToHomeList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 刷新按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,

        beginToHomeTime: undefined,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizToHomeAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizToHomeEditForm.handleUpdate(record, ids)
      );
    },
    /** 删除按钮操作 */
    handlezuofei(row) {
      var that = this;
      const bizToHomeIds = row.id || this.ids;
      if (bizToHomeIds.length <= 0) {
        that.$message.warning("选择作废预约上门数据", 3);
        return;
      }
      this.$confirm({
        title: "确认作废所选中数据?",
        onOk() {
          return delBizToHome(bizToHomeIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("操作成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportBizToHome(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
    // 选择修改时间

    updateyuyueDate(date, dateString, record) {
      this.toHomeInfo = record;
      this.toHomeInfo.yuyueTime = dateString;
      console.log(record, date, dateString);
    },
    updateyuyueDateOk() {
      if (this.toHomeInfo.id) {
        updateBizToHome(this.toHomeInfo).then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功", 3);
            this.getList();
          }
        });
      }
    },
  },
};
</script>
